<?php
// 在文件最顶部添加缓存控制
header("Cache-Control: max-age=300, must-revalidate");
header("Content-Type: text/html; charset=utf-8");

require_once __DIR__ . '/functions.php';

// 检查登录
if (!isLoggedIn()) {
    redirect('index.php', '请先登录', 'warning');
}

$userInfo = getUserInfo();

// 获取筛选条件
$status = $_GET['status'] ?? '';
$tracking_no = $_GET['tracking_no'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;

// 构建查询条件
$where = ['s.user_id = ?'];
$params = [$userInfo['id']];

if ($status && in_array($status, ['pending', 'completed'])) {
    $where[] = 's.status = ?';
    $params[] = $status;
}

if ($tracking_no) {
    // 通过物流单号筛选关联的订单
    $where[] = 's.id IN (SELECT DISTINCT s2.id FROM settlements s2 
                LEFT JOIN orders o ON JSON_CONTAINS(s2.order_ids, CAST(o.id AS JSON), \'$\')
                WHERE o.tracking_no LIKE ? AND s2.user_id = ?)';
    $params[] = "%$tracking_no%";
    $params[] = $userInfo['id'];
}

$whereClause = implode(' AND ', $where);

// 获取结算记录总数
$db = getDB();
$stmt = $db->prepare("SELECT COUNT(*) FROM settlements s WHERE $whereClause");
$stmt->execute($params);
$total = $stmt->fetchColumn();

// 计算分页
$totalPages = ceil($total / $perPage);
$page = min($page, $totalPages ?: 1);
$offset = ($page - 1) * $perPage;

// 获取结算记录列表
$stmt = $db->prepare("SELECT s.* FROM settlements s 
                     WHERE $whereClause 
                     ORDER BY s.created_at DESC 
                     LIMIT $offset, $perPage");
$stmt->execute($params);
$settlements = $stmt->fetchAll();

include __DIR__ . '/header.php';
?>

<div class="container-fluid px-3 px-md-4">
    <div class="row">
        <div class="col-12">
            <!-- 页面标题 -->
            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h1 class="h4 mb-1">
                        <i class="bi bi-receipt text-primary" aria-hidden="true"></i> 我的账单
                    </h1>
                    <p class="text-muted mb-0">共 <?php echo $total; ?> 条记录</p>
                </div>
                <button class="btn btn-primary d-md-none" type="button" data-bs-toggle="collapse" data-bs-target="#filterCollapse" aria-expanded="false" aria-controls="filterCollapse">
                    <i class="bi bi-funnel" aria-hidden="true"></i> 筛选
                </button>
            </div>

            <!-- 统计信息 - 移动端优化 -->
            <div class="row mb-4 g-2">
                <div class="col-6 col-sm-3">
                    <div class="card bg-warning text-white h-100">
                        <div class="card-body p-3 text-center">
                            <div class="d-flex align-items-center justify-content-center mb-2">
                                <i class="bi bi-clock-history fs-5" aria-hidden="true"></i>
                            </div>
                            <h2 class="card-title mb-1 fs-6">待结算</h2>
                            <?php
                            $stmt = $db->prepare("SELECT COUNT(*) FROM settlements WHERE user_id = ? AND status = 'pending'");
                            $stmt->execute([$userInfo['id']]);
                            $pendingCount = $stmt->fetchColumn();
                            ?>
                            <p class="mb-0 fw-bold fs-5"><?php echo $pendingCount; ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-6 col-sm-3">
                    <div class="card bg-success text-white h-100">
                        <div class="card-body p-3 text-center">
                            <div class="d-flex align-items-center justify-content-center mb-2">
                                <i class="bi bi-check-circle fs-5" aria-hidden="true"></i>
                            </div>
                            <h2 class="card-title mb-1 fs-6">已结算</h2>
                            <?php
                            $stmt = $db->prepare("SELECT COUNT(*) FROM settlements WHERE user_id = ? AND status = 'completed'");
                            $stmt->execute([$userInfo['id']]);
                            $completedCount = $stmt->fetchColumn();
                            ?>
                            <p class="mb-0 fw-bold fs-5"><?php echo $completedCount; ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-6 col-sm-3">
                    <div class="card bg-info text-white h-100">
                        <div class="card-body p-3 text-center">
                            <div class="d-flex align-items-center justify-content-center mb-2">
                                <i class="bi bi-currency-yen fs-5" aria-hidden="true"></i>
                            </div>
                            <h2 class="card-title mb-1 fs-6">待结金额</h2>
                            <?php
                            $stmt = $db->prepare("SELECT SUM(total_amount) FROM settlements WHERE user_id = ? AND status = 'pending'");
                            $stmt->execute([$userInfo['id']]);
                            $pendingAmount = $stmt->fetchColumn() ?: 0;
                            ?>
                            <p class="mb-0 fw-bold fs-5"><?php echo formatAmount($pendingAmount); ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-6 col-sm-3">
                    <div class="card bg-primary text-white h-100">
                        <div class="card-body p-3 text-center">
                            <div class="d-flex align-items-center justify-content-center mb-2">
                                <i class="bi bi-currency-yen fs-5" aria-hidden="true"></i>
                            </div>
                            <h2 class="card-title mb-1 fs-6">已结金额</h2>
                            <?php
                            $stmt = $db->prepare("SELECT SUM(total_amount) FROM settlements WHERE user_id = ? AND status = 'completed'");
                            $stmt->execute([$userInfo['id']]);
                            $completedAmount = $stmt->fetchColumn() ?: 0;
                            ?>
                            <p class="mb-0 fw-bold fs-5"><?php echo formatAmount($completedAmount); ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 筛选器 - 移动端可折叠 -->
            <div class="card mb-4">
                <div class="card-body p-3">
                    <div class="collapse d-md-block" id="filterCollapse">
                        <form method="GET" class="row g-3">
                            <div class="col-12 col-md-4">
                                <label for="status" class="form-label">结算状态</label>
                                <select class="form-select form-select-sm" id="status" name="status" aria-label="选择结算状态">
                                    <option value="">全部状态</option>
                                    <option value="pending" <?php echo $status == 'pending' ? 'selected' : ''; ?>>待结算</option>
                                    <option value="completed" <?php echo $status == 'completed' ? 'selected' : ''; ?>>已结算</option>
                                </select>
                            </div>
                            <div class="col-12 col-md-4">
                                <label for="tracking_no" class="form-label">物流单号</label>
                                <input type="text" class="form-control form-control-sm" id="tracking_no" name="tracking_no" 
                                       value="<?php echo htmlspecialchars($tracking_no); ?>" placeholder="输入物流单号" aria-label="输入物流单号进行筛选">
                            </div>
                            <div class="col-12 col-md-4 d-flex align-items-end">
                                <div class="d-grid d-md-flex gap-2 w-100">
                                    <button type="submit" class="btn btn-primary btn-sm" aria-label="搜索账单">
                                        <i class="bi bi-search" aria-hidden="true"></i> 搜索
                                    </button>
                                    <a href="my_bills.php" class="btn btn-secondary btn-sm" aria-label="重置筛选条件">
                                        <i class="bi bi-arrow-counterclockwise" aria-hidden="true"></i> 重置
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- 结算记录列表 -->
            <div class="card">
                <div class="card-body p-0">
                    <?php if (empty($settlements)): ?>
                        <div class="text-center py-5">
                            <i class="bi bi-inbox display-1 text-muted" aria-hidden="true"></i>
                            <h2 class="mt-3 h5 text-muted">暂无账单记录</h2>
                            <p class="text-muted">您还没有任何结算记录</p>
                            <a href="submit.php" class="btn btn-primary mt-3">
                                <i class="bi bi-plus-circle" aria-hidden="true"></i> 去提交订单
                            </a>
                        </div>
                    <?php else: ?>
                        <!-- 移动端卡片视图 -->
                        <div class="d-md-none">
                            <?php foreach ($settlements as $settlement): ?>
                                <?php 
                                $orderIds = json_decode($settlement['order_ids'], true);
                                $orderCount = count($orderIds ?: []);
                                ?>
                                <div class="border-bottom p-3 settlement-card" data-id="<?php echo $settlement['id']; ?>" role="button" tabindex="0" aria-label="查看结算详情 ID: <?php echo $settlement['id']; ?>">
                                    <div class="d-flex justify-content-between align-items-start mb-2">
                                        <div>
                                            <span class="badge bg-<?php echo $settlement['status'] == 'completed' ? 'success' : 'warning'; ?> mb-1">
                                                <?php echo $settlement['status'] == 'completed' ? '已结算' : '待结算'; ?>
                                            </span>
                                            <span class="badge bg-<?php echo $settlement['settlement_type'] == 'commission' ? 'info' : 'primary'; ?>">
                                                <?php echo $settlement['settlement_type'] == 'commission' ? '本金' : '本金+佣金'; ?>
                                            </span>
                                        </div>
                                        <small class="text-muted">#<?php echo $settlement['id']; ?></small>
                                    </div>
                                    
                                    <div class="mb-2">
                                        <span class="text-<?php echo $settlement['status'] == 'completed' ? 'success' : 'warning'; ?> fw-bold fs-5">
                                            <?php echo formatAmount($settlement['total_amount']); ?>
                                        </span>
                                    </div>
                                    
                                    <div class="row g-2 text-muted small mb-2">
                                        <div class="col-6">
                                            <i class="bi bi-box" aria-hidden="true"></i> <?php echo $orderCount; ?> 个订单
                                        </div>
                                        <div class="col-6 text-end">
                                            <i class="bi bi-calendar" aria-hidden="true"></i> <?php echo date('m-d H:i', strtotime($settlement['created_at'])); ?>
                                        </div>
                                    </div>
                                    
                                    <div class="d-flex justify-content-between align-items-center">
                                        <?php if ($settlement['settled_at']): ?>
                                            <small class="text-success">
                                                <i class="bi bi-check-circle" aria-hidden="true"></i> <?php echo date('m-d H:i', strtotime($settlement['settled_at'])); ?>
                                            </small>
                                        <?php else: ?>
                                            <small class="text-warning">
                                                <i class="bi bi-clock" aria-hidden="true"></i> 待结算
                                            </small>
                                        <?php endif; ?>
                                        
                                        <button type="button" class="btn btn-sm btn-outline-primary view-details-btn" 
                                                data-id="<?php echo $settlement['id']; ?>" 
                                                aria-label="查看结算详情 ID: <?php echo $settlement['id']; ?>">
                                            <i class="bi bi-eye" aria-hidden="true"></i> 详情
                                        </button>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <!-- 桌面端表格视图 -->
                        <div class="table-responsive d-none d-md-block">
                            <table class="table table-hover mb-0" aria-label="结算记录列表">
                                <thead class="table-light">
                                    <tr>
                                        <th scope="col" width="80">ID</th>
                                        <th scope="col" width="120">结算类型</th>
                                        <th scope="col" width="120">总金额</th>
                                        <th scope="col" width="100">订单数量</th>
                                        <th scope="col" width="100">状态</th>
                                        <th scope="col" width="150">创建时间</th>
                                        <th scope="col" width="150">结算时间</th>
                                        <th scope="col" width="80">操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($settlements as $settlement): ?>
                                        <tr>
                                            <td><?php echo $settlement['id']; ?></td>
                                            <td>
                                                <span class="badge bg-<?php echo $settlement['settlement_type'] == 'commission' ? 'info' : 'primary'; ?>">
                                                    <?php echo $settlement['settlement_type'] == 'commission' ? '本金' : '本金+佣金'; ?>
                                                </span>
                                            </td>
                                            <td class="text-<?php echo $settlement['status'] == 'completed' ? 'success' : 'warning'; ?> fw-bold">
                                                <?php echo formatAmount($settlement['total_amount']); ?>
                                            </td>
                                            <td>
                                                <?php 
                                                $orderIds = json_decode($settlement['order_ids'], true);
                                                echo count($orderIds ?: []);
                                                ?>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo $settlement['status'] == 'completed' ? 'success' : 'warning'; ?>">
                                                    <?php echo $settlement['status'] == 'completed' ? '已结算' : '待结算'; ?>
                                                </span>
                                            </td>
                                            <td><?php echo formatTime($settlement['created_at']); ?></td>
                                            <td>
                                                <?php if ($settlement['settled_at']): ?>
                                                    <?php echo formatTime($settlement['settled_at']); ?>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <button type="button" class="btn btn-sm btn-outline-primary view-details-btn" 
                                                        data-id="<?php echo $settlement['id']; ?>"
                                                        data-bs-toggle="tooltip" 
                                                        title="查看详情"
                                                        aria-label="查看结算详情 ID: <?php echo $settlement['id']; ?>">
                                                    <i class="bi bi-eye" aria-hidden="true"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- 分页 - 移动端优化 -->
                        <?php if ($totalPages > 1): ?>
                            <div class="p-3 border-top">
                                <nav aria-label="账单分页导航">
                                    <ul class="pagination justify-content-center pagination-sm mb-0">
                                        <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                            <a class="page-link" href="?page=<?php echo $page - 1; ?>&status=<?php echo $status; ?>&tracking_no=<?php echo urlencode($tracking_no); ?>" aria-label="上一页">
                                                <i class="bi bi-chevron-left" aria-hidden="true"></i>
                                            </a>
                                        </li>
                                        
                                        <?php 
                                        // 简化移动端分页显示
                                        $startPage = max(1, $page - 1);
                                        $endPage = min($totalPages, $page + 1);
                                        
                                        if ($startPage > 1): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=1&status=<?php echo $status; ?>&tracking_no=<?php echo urlencode($tracking_no); ?>" aria-label="第1页">1</a>
                                            </li>
                                            <?php if ($startPage > 2): ?>
                                                <li class="page-item disabled">
                                                    <span class="page-link" aria-hidden="true">...</span>
                                                </li>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                        
                                        <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                                            <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                                <a class="page-link" href="?page=<?php echo $i; ?>&status=<?php echo $status; ?>&tracking_no=<?php echo urlencode($tracking_no); ?>" aria-label="第<?php echo $i; ?>页" aria-current="<?php echo $i == $page ? 'page' : 'false'; ?>">
                                                    <?php echo $i; ?>
                                                </a>
                                            </li>
                                        <?php endfor; ?>
                                        
                                        <?php if ($endPage < $totalPages): ?>
                                            <?php if ($endPage < $totalPages - 1): ?>
                                                <li class="page-item disabled">
                                                    <span class="page-link" aria-hidden="true">...</span>
                                                </li>
                                            <?php endif; ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo $totalPages; ?>&status=<?php echo $status; ?>&tracking_no=<?php echo urlencode($tracking_no); ?>" aria-label="第<?php echo $totalPages; ?>页"><?php echo $totalPages; ?></a>
                                            </li>
                                        <?php endif; ?>
                                        
                                        <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                                            <a class="page-link" href="?page=<?php echo $page + 1; ?>&status=<?php echo $status; ?>&tracking_no=<?php echo urlencode($tracking_no); ?>" aria-label="下一页">
                                                <i class="bi bi-chevron-right" aria-hidden="true"></i>
                                            </a>
                                        </li>
                                    </ul>
                                    
                                    <!-- 移动端页码信息 -->
                                    <div class="text-center d-md-none mt-2">
                                        <small class="text-muted">
                                            第 <?php echo $page; ?> 页，共 <?php echo $totalPages; ?> 页，<?php echo $total; ?> 条记录
                                        </small>
                                    </div>
                                </nav>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 结算详情模态框 -->
<div class="modal fade" id="settlementDetailsModal" tabindex="-1" aria-labelledby="settlementDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title" id="settlementDetailsModalLabel">账单详情</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body" id="settlementDetailsContent">
                <!-- 详情内容将通过AJAX加载 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" aria-label="关闭对话框">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 图片查看模态框 -->
<div class="modal fade" id="imageModal" tabindex="-1" aria-labelledby="imageModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title" id="imageModalLabel">图片查看</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body text-center">
                <img id="modalImage" src="" class="img-fluid" style="max-height: 70vh;" alt="预览图片">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" aria-label="关闭图片预览">关闭</button>
            </div>
        </div>
    </div>
</div>

<script>
// 移动端优化函数
function initMobileOptimizations() {
    // 自动关闭筛选面板（移动端）
    if (window.innerWidth < 768) {
        const filterCollapse = document.getElementById('filterCollapse');
        if (filterCollapse && !filterCollapse.classList.contains('show')) {
            // 默认在移动端收起筛选面板
            new bootstrap.Collapse(filterCollapse, { toggle: false });
        }
    }
    
    console.log('初始化移动端优化，找到卡片数量：', document.querySelectorAll('.settlement-card').length);
    
    // 优化移动端卡片点击区域
    const mobileCards = document.querySelectorAll('.settlement-card');
    mobileCards.forEach(card => {
        card.style.cursor = 'pointer';
        // 移除之前的事件监听器，避免重复绑定
        card.removeEventListener('click', handleCardClick);
        card.removeEventListener('keypress', handleCardKeyPress);
        card.addEventListener('click', handleCardClick);
        card.addEventListener('keypress', handleCardKeyPress);
    });
}

// 处理卡片点击事件
function handleCardClick(e) {
    // 如果点击的不是按钮，则触发详情查看
    if (!e.target.closest('.view-details-btn')) {
        const settlementId = this.getAttribute('data-id');
        console.log('点击卡片，ID:', settlementId);
        showSettlementDetails(settlementId);
    }
}

// 处理卡片键盘事件（辅助功能）
function handleCardKeyPress(e) {
    if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        const settlementId = this.getAttribute('data-id');
        console.log('键盘操作卡片，ID:', settlementId);
        showSettlementDetails(settlementId);
    }
}

// 处理按钮点击事件
function handleButtonClick() {
    const settlementId = this.getAttribute('data-id');
    console.log('点击按钮，ID:', settlementId);
    showSettlementDetails(settlementId);
}

// 结算详情查看函数
function showSettlementDetails(settlementId) {
    console.log('查看详情，ID:', settlementId);
    
    if (!settlementId || settlementId === '0') {
        alert('结算记录ID无效');
        return;
    }
    
    // 显示加载状态
    document.getElementById('settlementDetailsContent').innerHTML = `
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-3">加载中...</p>
        </div>
    `;
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('settlementDetailsModal'));
    modal.show();
    
    // 加载结算详情
    fetch('api/settlement_details.php?id=' + settlementId)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            console.log('API响应:', data);
            if (data.success) {
                renderSettlementDetails(data.data);
            } else {
                document.getElementById('settlementDetailsContent').innerHTML = `
                    <div class="alert alert-danger">${data.message || '加载失败'}</div>
                `;
            }
        })
        .catch(error => {
            console.error('加载失败:', error);
            document.getElementById('settlementDetailsContent').innerHTML = `
                <div class="alert alert-danger">加载失败：${error.message}</div>
            `;
        });
}

// 渲染结算详情 - 优化移动端显示
function renderSettlementDetails(settlement) {
    const statusClass = {
        'pending': 'warning',
        'completed': 'success'
    };
    const statusText = {
        'pending': '待结算',
        'completed': '已结算'
    };
    const typeText = {
        'commission': '本金',
        'principal_commission': '本金+佣金'
    };
    
    let html = `
        <div class="settlement-details">
            <!-- 基本信息 -->
            <div class="row g-3 mb-4">
                <div class="col-12 col-md-6">
                    <div class="card">
                        <div class="card-header bg-light">
                            <h3 class="h6 mb-0">基本信息</h3>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-sm table-borderless" aria-label="结算基本信息">
                                    <tr>
                                        <td class="text-muted" width="40%">结算ID：</td>
                                        <td class="fw-bold">${settlement.id}</td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">结算类型：</td>
                                        <td>
                                            <span class="badge bg-${settlement.settlement_type == 'commission' ? 'info' : 'primary'}">
                                                ${typeText[settlement.settlement_type]}
                                            </span>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">总金额：</td>
                                        <td class="text-primary fw-bold fs-5">
                                            ¥${parseFloat(settlement.total_amount).toFixed(2)}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">状态：</td>
                                        <td>
                                            <span class="badge bg-${statusClass[settlement.status]}">
                                                ${statusText[settlement.status]}
                                            </span>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted">创建时间：</td>
                                        <td>${new Date(settlement.created_at).toLocaleString('zh-CN')}</td>
                                    </tr>
    `;
    
    if (settlement.settled_at) {
        html += `
            <tr>
                <td class="text-muted">结算时间：</td>
                <td>${new Date(settlement.settled_at).toLocaleString('zh-CN')}</td>
            </tr>
        `;
    }
    
    html += `
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-12 col-md-6">
                    <div class="card">
                        <div class="card-header bg-light">
                            <h3 class="h6 mb-0">结算信息</h3>
                        </div>
                        <div class="card-body">
    `;
    
    if (settlement.settlement_info) {
        html += `
            <div class="border rounded p-3 bg-light">
                ${settlement.settlement_info.replace(/\n/g, '<br>')}
            </div>
        `;
    } else {
        html += `<p class="text-muted mb-0">暂无结算信息</p>`;
    }
    
    // 结算截图
    if (settlement.settlement_screenshots && settlement.settlement_screenshots.length > 0) {
        html += `
            <div class="mt-3">
                <h4 class="h6 mb-2">结算截图</h4>
                <div class="row g-2">
        `;
        settlement.settlement_screenshots.forEach((screenshot, index) => {
            html += `
                <div class="col-6 col-sm-4">
                    <div class="text-center">
                        <img src="${screenshot}" 
                             class="img-fluid rounded border" 
                             style="max-height: 120px; cursor: pointer;" 
                             onclick="showImageModal('${screenshot}')" 
                             alt="结算截图 ${index + 1}"
                             aria-label="结算截图 ${index + 1}，点击查看大图">
                        <div class="mt-1">
                            <small class="text-muted">点击查看</small>
                        </div>
                    </div>
                </div>
            `;
        });
        html += `</div></div>`;
    }
    
    html += `
                        </div>
                    </div>
                </div>
            </div>

            <!-- 关联订单 -->
            <div class="card mb-4">
                <div class="card-header bg-light d-flex justify-content-between align-items-center">
                    <h3 class="h6 mb-0">关联订单 (${settlement.order_count || 0}个)</h3>
                    <span class="badge bg-primary">${settlement.order_count || 0}</span>
                </div>
                <div class="card-body p-0">
    `;
    
    if (settlement.orders && settlement.orders.length > 0) {
        // 移动端使用卡片布局，桌面端使用表格
        html += `
            <!-- 移动端卡片布局 -->
            <div class="d-md-none">
        `;
        
        settlement.orders.forEach((order, index) => {
            const statusClass = {
                'pending': 'warning',
                'settled': 'success',
                'refunded': 'danger'
            };
            const statusText = {
                'pending': '未结算',
                'settled': '已结算',
                'refunded': '已退还'
            };
            
            html += `
                <div class="border-bottom p-3">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <span class="badge bg-secondary">订单 #${order.id}</span>
                        <span class="badge bg-${statusClass[order.status]}">
                            ${statusText[order.status]}
                        </span>
                    </div>
                    
                    <div class="mb-2">
                        <strong>${order.product_name}</strong>
                    </div>
                    
                    <div class="row g-2 small text-muted">
                        <div class="col-6">
                            <i class="bi bi-geo-alt" aria-hidden="true"></i> ${order.delivery_location_label || order.delivery_location}
                        </div>
                        <div class="col-6">
                            <i class="bi bi-shop" aria-hidden="true"></i> ${order.order_platform_label || order.order_platform}
                        </div>
                        <div class="col-12">
                            <i class="bi bi-truck" aria-hidden="true"></i> 物流: <code>${order.tracking_no}</code>
                        </div>
                        <div class="col-6">
                            <i class="bi bi-currency-yen" aria-hidden="true"></i> 金额: ¥${parseFloat(order.order_amount).toFixed(2)}
                        </div>
                        <div class="col-6">
                            <i class="bi bi-cash-coin" aria-hidden="true"></i> 结算: ¥${parseFloat(order.settlement_amount || order.order_amount).toFixed(2)}
                        </div>
                    </div>
                    
                    ${order.screenshot_url ? `
                    <div class="mt-2">
                        <small class="text-muted">订单截图:</small>
                        <div>
                            <img src="${order.screenshot_url}" 
                                 class="img-thumbnail" 
                                 style="max-height: 80px; cursor: pointer;" 
                                 onclick="showImageModal('${order.screenshot_url}')" 
                                 alt="订单 ${order.id} 的截图"
                                 aria-label="订单 ${order.id} 的截图，点击查看大图">
                        </div>
                    </div>
                    ` : ''}
                </div>
            `;
        });
        
        html += `</div>`;
        
        // 桌面端表格布局
        html += `
            <div class="d-none d-md-block">
                <div class="table-responsive">
                    <table class="table table-sm table-striped mb-0" aria-label="关联订单列表">
                        <thead class="table-light">
                            <tr>
                                <th scope="col">订单ID</th>
                                <th scope="col">商品名称</th>
                                <th scope="col">收货地</th>
                                <th scope="col">下单平台</th>
                                <th scope="col">物流单号</th>
                                <th scope="col">下单金额</th>
                                <th scope="col">结算金额</th>
                                <th scope="col">状态</th>
                                <th scope="col">截图</th>
                            </tr>
                        </thead>
                        <tbody>
        `;
        
        settlement.orders.forEach(order => {
            const statusClass = {
                'pending': 'warning',
                'settled': 'success',
                'refunded': 'danger'
            };
            const statusText = {
                'pending': '未结算',
                'settled': '已结算',
                'refunded': '已退还'
            };
            
            html += `
                <tr>
                    <td>${order.id}</td>
                    <td>
                        <span class="d-inline-block text-truncate" style="max-width: 150px;">
                            ${order.product_name}
                        </span>
                    </td>
                    <td>${order.delivery_location_label || order.delivery_location}</td>
                    <td>${order.order_platform_label || order.order_platform}</td>
                    <td><code class="small">${order.tracking_no}</code></td>
                    <td class="text-nowrap">¥${parseFloat(order.order_amount).toFixed(2)}</td>
                    <td class="text-success fw-bold text-nowrap">¥${parseFloat(order.settlement_amount || order.order_amount).toFixed(2)}</td>
                    <td>
                        <span class="badge bg-${statusClass[order.status]}">
                            ${statusText[order.status]}
                        </span>
                    </td>
                    <td>
            `;
            
            if (order.screenshot_url) {
                html += `
                    <img src="${order.screenshot_url}" 
                         class="img-thumbnail" 
                         style="max-height: 40px; cursor: pointer;" 
                         onclick="showImageModal('${order.screenshot_url}')" 
                         alt="订单 ${order.id} 截图"
                         aria-label="订单 ${order.id} 截图，点击查看大图">
                `;
            } else {
                html += `<span class="text-muted small">无</span>`;
            }
            
            html += `</td></tr>`;
        });
        
        html += `</tbody></table></div></div>`;
    } else {
        html += `
            <div class="text-center py-4">
                <p class="text-muted mb-0">暂无订单数据</p>
            </div>
        `;
    }
    
    html += `</div></div>`;
    
    // 结算明细
    if (settlement.details && settlement.details.length > 0) {
        html += `
            <div class="card">
                <div class="card-header bg-light d-flex justify-content-between align-items-center">
                    <h3 class="h6 mb-0">结算明细记录 (${settlement.details.length}条)</h3>
                    <span class="badge bg-info">${settlement.details.length}</span>
                </div>
                <div class="card-body p-0">
        `;
        
        // 移动端卡片布局
        html += `
            <div class="d-md-none">
        `;
        
        settlement.details.forEach((detail, index) => {
            html += `
                <div class="border-bottom p-3">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <span class="badge bg-secondary">明细 #${index + 1}</span>
                        <span class="badge bg-${detail.settlement_type === 'commission' ? 'info' : 'primary'}">
                            ${typeText[detail.settlement_type]}
                        </span>
                    </div>
                    
                    <div class="row g-2 small">
                        <div class="col-6">
                            <strong>订单ID:</strong> ${detail.order_id}
                        </div>
                        <div class="col-6">
                            <strong>商品:</strong> ${detail.product_name || 'N/A'}
                        </div>
                        <div class="col-12">
                            <strong>结算金额:</strong> 
                            <span class="text-success fw-bold">
                                ¥${parseFloat(detail.settlement_amount).toFixed(2)}
                            </span>
                        </div>
                        <div class="col-12">
                            <strong>结算时间:</strong> ${new Date(detail.created_at).toLocaleString('zh-CN')}
                        </div>
                        ${detail.settlement_info ? `
                        <div class="col-12">
                            <strong>结算信息:</strong> 
                            <div class="border rounded p-2 bg-light mt-1">
                                ${detail.settlement_info.replace(/\n/g, '<br>')}
                            </div>
                        </div>
                        ` : ''}
                    </div>
                    
                    ${detail.screenshot_urls && detail.screenshot_urls.length > 0 ? `
                        <div class="mt-2">
                            <strong class="small">操作截图:</strong>
                            <div class="row g-2 mt-1">
                                ${detail.screenshot_urls.map((url, imgIndex) => `
                                    <div class="col-4">
                                        <img src="${url}" 
                                             class="img-thumbnail w-100" 
                                             style="max-height: 100px; cursor: pointer;" 
                                             onclick="showImageModal('${url}')" 
                                             alt="操作截图 ${imgIndex + 1}"
                                             aria-label="操作截图 ${imgIndex + 1}，点击查看大图">
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    ` : ''}
                </div>
            `;
        });
        
        html += `</div>`;
        
        // 桌面端表格布局
        html += `
            <div class="d-none d-md-block">
                <div class="table-responsive">
                    <table class="table table-sm table-striped mb-0" aria-label="结算明细记录">
                        <thead class="table-light">
                            <tr>
                                <th scope="col">订单ID</th>
                                <th scope="col">商品名称</th>
                                <th scope="col">结算类型</th>
                                <th scope="col">结算金额</th>
                                <th scope="col">结算信息</th>
                                <th scope="col">结算时间</th>
                                <th scope="col">操作截图</th>
                            </tr>
                        </thead>
                        <tbody>
        `;
        
        settlement.details.forEach(detail => {
            html += `
                <tr>
                    <td>${detail.order_id}</td>
                    <td>
                        <span class="d-inline-block text-truncate" style="max-width: 150px;">
                            ${detail.product_name || 'N/A'}
                        </span>
                    </td>
                    <td>
                        <span class="badge bg-${detail.settlement_type === 'commission' ? 'info' : 'primary'}">
                            ${typeText[detail.settlement_type]}
                        </span>
                    </td>
                    <td class="text-success fw-bold text-nowrap">
                        ¥${parseFloat(detail.settlement_amount).toFixed(2)}
                    </td>
                    <td>
                        ${detail.settlement_info ? `
                            <span class="d-inline-block text-truncate" style="max-width: 200px;" 
                                  data-bs-toggle="tooltip" title="${detail.settlement_info.replace(/"/g, '&quot;')}">
                                ${detail.settlement_info}
                            </span>
                        ` : '-'}
                    </td>
                    <td>${new Date(detail.created_at).toLocaleString('zh-CN')}</td>
                    <td>
            `;
            
            if (detail.screenshot_urls && detail.screenshot_urls.length > 0) {
                detail.screenshot_urls.forEach((url, index) => {
                    html += `
                        <img src="${url}" 
                             class="img-thumbnail me-1" 
                             style="max-height: 40px; max-width: 40px; cursor: pointer;" 
                             onclick="showImageModal('${url}')" 
                             alt="操作截图 ${index + 1}"
                             aria-label="操作截图 ${index + 1}，点击查看大图">
                    `;
                });
            } else {
                html += `<span class="text-muted small">无截图</span>`;
            }
            
            html += `</td></tr>`;
        });
        
        html += `</tbody></table></div></div></div></div>`;
    }
    
    html += `</div>`;
    
    document.getElementById('settlementDetailsContent').innerHTML = html;
    
    // 初始化工具提示
    setTimeout(() => {
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }, 100);
}

// 图片查看函数
function showImageModal(imageUrl) {
    document.getElementById('modalImage').src = imageUrl;
    const modal = new bootstrap.Modal(document.getElementById('imageModal'));
    modal.show();
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM 加载完成，开始初始化');
    
    // 绑定详情查看按钮事件
    const buttons = document.querySelectorAll('.view-details-btn');
    console.log('找到按钮数量:', buttons.length);
    
    buttons.forEach(btn => {
        // 移除之前的事件监听器，避免重复绑定
        btn.removeEventListener('click', handleButtonClick);
        btn.addEventListener('click', handleButtonClick);
    });
    
    initMobileOptimizations();
    
    // 初始化工具提示
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});

// 监听窗口大小变化，优化移动端体验
window.addEventListener('resize', function() {
    console.log('窗口大小改变，重新初始化移动端优化');
    initMobileOptimizations();
});

// 添加全局错误处理
window.addEventListener('error', function(e) {
    console.error('全局错误:', e.error);
});

// 确保所有函数都在全局作用域
window.showImageModal = showImageModal;
window.showSettlementDetails = showSettlementDetails;
</script>

<style>
/* 移动端优化样式 */
@media (max-width: 767.98px) {
    .container-fluid {
        padding-left: 12px;
        padding-right: 12px;
    }
    
    .card-body {
        padding: 1rem;
    }
    
    .btn-sm {
        padding: 0.25rem 0.5rem;
        font-size: 0.875rem;
    }
    
    /* 移动端卡片悬停效果 */
    .settlement-card {
        transition: all 0.2s ease;
    }
    
    .settlement-card:active {
        background-color: rgba(0, 0, 0, 0.05);
        transform: scale(0.99);
    }
    
    /* 移动端模态框优化 */
    .modal-dialog {
        margin: 0.5rem;
    }
    
    .modal-content {
        border-radius: 0.5rem;
    }
    
    /* 移动端分页优化 */
    .pagination-sm .page-link {
        padding: 0.375rem 0.75rem;
        font-size: 0.875rem;
    }
    
    /* 统计卡片移动端优化 */
    .card .card-body {
        padding: 0.75rem;
    }
    
    .card .card-title {
        font-size: 0.875rem;
        margin-bottom: 0.5rem;
    }
    
    .card h5 {
        font-size: 1.25rem;
    }
    
    /* 移动端详情卡片优化 */
    .settlement-details .border-bottom {
        padding: 1rem;
    }
    
    .settlement-details .small {
        font-size: 0.8rem;
    }
    
    /* 移动端图片优化 */
    .img-thumbnail {
        max-height: 80px;
        object-fit: cover;
    }
}

/* 通用优化 */
.text-truncate-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

/* 图片预览优化 */
.img-thumbnail {
    transition: all 0.3s ease;
    cursor: pointer;
}

.img-thumbnail:hover {
    transform: scale(1.05);
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
}

/* 加载动画优化 */
.spinner-border {
    width: 2rem;
    height: 2rem;
}

/* 移动端表格单元格优化 */
.table td, .table th {
    padding: 0.75rem 0.5rem;
}

/* 兼容性修复 */
.text-size-adjust {
    text-size-adjust: 100%;
    -webkit-text-size-adjust: 100%;
    -moz-text-size-adjust: 100%;
    -ms-text-size-adjust: 100%;
}

.backdrop-filter {
    backdrop-filter: blur(5px);
    -webkit-backdrop-filter: blur(5px);
}

.text-align-match {
    text-align: match-parent;
    text-align: -webkit-match-parent;
}

.print-color-adjust {
    color-adjust: exact;
    -webkit-print-color-adjust: exact;
}

@media (max-width: 575.98px) {
    .table td, .table th {
        padding: 0.5rem 0.25rem;
        font-size: 0.875rem;
    }
    
    /* 移动端模态框全屏 */
    .modal-dialog {
        margin: 0;
        max-width: 100%;
        height: 100%;
    }
    
    .modal-content {
        height: 100%;
        border-radius: 0;
    }
    
    .modal-body {
        overflow-y: auto;
    }
    
    /* 移动端详情信息优化 */
    .settlement-details .row.g-2 > [class*="col-"] {
        margin-bottom: 0.5rem;
    }
    
    .settlement-details code {
        font-size: 0.75rem;
        word-break: break-all;
    }
}

/* 卡片悬停效果 */
.card {
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.12);
}

/* 状态徽章优化 */
.badge {
    font-size: 0.75em;
}

/* 筛选表单优化 */
.form-select-sm, .form-control-sm {
    font-size: 0.875rem;
}

/* 分页激活状态 */
.page-item.active .page-link {
    background-color: var(--primary-color);
    border-color: var(--primary-color);
}

/* 详情卡片内部间距优化 */
.settlement-details .border-bottom:last-child {
    border-bottom: none !important;
}

/* 移动端文字换行优化 */
.text-break-mobile {
    word-break: break-word;
    overflow-wrap: break-word;
}

/* 移动端图标和文字对齐 */
.small i {
    width: 16px;
    text-align: center;
}

/* 焦点样式优化 */
.btn:focus, .page-link:focus, .form-control:focus, .form-select:focus {
    outline: 2px solid var(--primary-color);
    outline-offset: 2px;
}

.settlement-card:focus {
    outline: 2px solid var(--primary-color);
    outline-offset: 2px;
    background-color: rgba(0, 0, 0, 0.05);
}
</style>

<?php include __DIR__ . '/footer.php'; ?>